import  React, { forwardRef,useEffect,useRef } from "react"
import './index.scss';
import cx from 'classnames';
import { Observer } from "../../utils/observe";
export interface ViewProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
 row?:boolean;
 align?: 'start' | 'center' | 'end' | 'baseline' | 'stretch';
 justify?: 'start' | 'center' | 'end' | 'between';
 wrap?:boolean
 /**出现在屏幕事件 */
 onAppear?:()=>void;
/** 消失在屏幕事件*/
 disAppear?:()=>void;
}

const FLEX_MAP = {
    start: 'flex-start',
    center: 'center',
    end: 'flex-end',
    baseline: 'baseline',
    stretch: 'stretch',
    between: 'space-between',
} as const

function InnerView({
    className,children,style,row=false,align,justify,propsRef, wrap,...restProps
}:ViewProps & { propsRef?: React.ForwardedRef<HTMLDivElement | null> }):JSX.Element {


return (
    <div className={cx('brick-base-view',className)} 
     style={{
         flexDirection:row?'row':'column',
         alignItems:align &&FLEX_MAP[align],
         justifyContent:justify&&FLEX_MAP[justify],
         flexWrap:wrap?'wrap':undefined,
         ...style
     }}
     ref={propsRef}
     {...restProps}   // onAppear和disAppear会被拦截 不会被当成Props传递给div
    >
        {children}
    </div>
)
}
function ObserveView({onAppear,disAppear,propsRef,...resetProps}:ViewProps &{propsRef:React.ForwardedRef<HTMLDivElement | null>}):JSX.Element{
 const refDiv = useRef<HTMLDivElement | null>(null);
 const appearHandle  = useRef<()=>void>(null);
 const disappearHandle = useRef<()=>void>(null);
 useEffect(()=>{
     appearHandle.current = onAppear;
     disappearHandle.current = disAppear;
 })
 // 这部分有点没看懂 为什么不加依赖项
  useEffect(()=>{
     if(refDiv.current){  // 表示
        Observer(refDiv.current,inView=>{
            console.log('inVeiw',inView);
            if(inView){
                appearHandle.current && appearHandle.current();
            }else{
                disappearHandle.current && disappearHandle.current();
            }
        })
       
     }
 },[])

const addRef  = (r:HTMLDivElement)=>{
   refDiv.current = r;
   if( typeof propsRef==='function'){
     propsRef(r);
   }else if(propsRef){
       propsRef.current = r;
   }
}
return <InnerView {...resetProps} propsRef={addRef}/>
}



const View  = forwardRef<HTMLDivElement | null,ViewProps>((props,ref)=>{
  const {onAppear,disAppear,...resetProps} = props
if(onAppear || disAppear){
  return <ObserveView {...props} propsRef={ref}/>
}

  return <InnerView {...resetProps} propsRef={ref}/>
})


export default View;

